<?php

/**
 * @Author: CraspH2b
 * @Date:   2018-01-22 11:49:45
 * @Email:   646054215@qq.com
 * @Last Modified time: 2018-07-03 14:58:15
 */
namespace app\admin\model;
use think\Model;
use think\Validate;
use think\Request;
use think\Db;
use think\Auth;

class AuthRule extends Model{
	protected $nocheck_url = ['Admin/Index/index'];
	protected $nocheck_id  = ['1'];
	/**
	 * 添加菜单
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function menu_add($data){
       $rule = [
          'title'  => 'require|unique:auth_rule',
          'name'  => 'require',

	      ];

	      $msg = [
	          'title.require' => '操作名不能为空',
	          'title.unique' => '操作名不能重复',
	          'name.require' => '控制器/方法不能为空',
	      ];
	      $data['addtime'] = time();
	      $validate = new Validate($rule, $msg);
	      $result   = $validate->check($data);
	      $data['notcheck'] = isset($data['notcheck'])?$data['notcheck']:'0';
	      $data['status'] = isset($data['status'])?$data['status']:'0';
          if($data['pid'] == '0'){
          	 $data['level'] = 1;
          }else{
          	 $level = $this->where('id',$data['pid'])->value('level');
             $data['level'] = $level + 1;
          }
	      if($result){
	         if(self::save($data)){
	            return true;
	         }else{
	            $this->error = "添加菜单失败";
	            return false;
	         }
	      }else{
	         $this->error = $validate->getError();
	         return false;
	      }
	}
	public function menu_edit($data){
		if($data['pid'] == $data['id']){
			$this->error = "菜单上一级不能是自己";
            return false;		  	  
		}		
       $rule = [
          'title'  => 'require|unique:auth_rule',
          'name'  => 'require',

	      ];

	      $msg = [
	          'title.require' => '操作名不能为空',
	          'title.unique' => '操作名不能重复',
	          'name.require' => '控制器/方法不能为空',
	      ];
	      $validate = new Validate($rule, $msg);
	      $result   = $validate->check($data);
	      $data['notcheck'] = isset($data['notcheck'])?$data['notcheck']:'0';
	      $data['status'] = isset($data['status'])?$data['status']:'0';
	      if($result){
	         //判断是否更改了pid
			  $menu = $this->where('id',$data['id'])->field('pid,level')->find();
			  if(!isset($data['status'])) $data['status'] = 0;
			  if($menu['pid'] == $data['pid']){//未更改pid
			  	  if(self::update($data)){
			          return true;
			      }else{
			         $this->error = "修改菜单失败";
			         return false;
			      }
			  }else{
			  	$id = $data['id'];
			  	//找到移动到此的level
			  	if($data['pid'] == 0){
			  		$get_level = 1;
			  		$data['level'] = 1;
			  	}else{
			  		$get_level = $this->where('id',$data['pid'])->value('level');
			  		$data['level'] = $get_level + 1;
			  	}
			  	$level = $menu['level'];//当前的level
			  	if(self::update($data)){
			  		$childs_ids = $this-> get_child_id($data['id']);
			  		if($level > $get_level){ //放到比之前level低的，即由3-1
						//修改子类
	                	if($data['pid'] == 0){
	                		$sub_level_dec = $level - $get_level;
	                	}else{
	                		$sub_level_dec = $level - $get_level - 1;
	                	}
	                	$this->where('id','in',$childs_ids)->setDec('level',$sub_level_dec);		  			
			  		}else{    //放到比之前level高的的，即由1-3
						//修改子类
	                	$sub_level_dec = $get_level - $level + 1;
	                	$this->where('id','in',$childs_ids)->setInc('level',$sub_level_dec);		  			
			  		}
	                return true;
				}else{
	                $this->error = "修改菜单失败";
	                return false;
	            }		  		

			  }    
	      }else{
	         $this->error = $validate->getError();
	         return false;
	      }
	}
	/**
   * 更新菜单状态
   * @param  [type] $id [管理员id]
   * @return [type]     [description]
   */
	  public function menu_status($id){
	      $status = $this->where('id',$id)->value('status');
	      $res = [];
	      if($status == '1'){
	        if($this->where('id',$id)->setField('status','0')){
	          $res = ['code'=>'1','msg'=>'隐藏','btn'=>'0','url'=>url('admin/Sys/menu')];
	        }else{
	          $res = ['code'=>'0','msg'=>'修改失败'];
	        }
	      }else{
	          if($this->where('id',$id)->setField('status','1')){
	          $res = ['code'=>'1','msg'=>'显示','btn'=>'1','url'=>url('admin/Sys/menu')];
	        }else{
	          $res = ['code'=>'0','msg'=>'修改失败'];
	        }
	      }
	      return $res;
	  }
	  /**
	   * 更新菜单检测状态
	   * @param  [type] $id [管理员id]
	   * @return [type]     [description]
	   */
	  public function menu_notcheck($id){
	      $status = $this->where('id',$id)->value('notcheck');
	      $res = [];
	      if($status == '1'){
	        if($this->where('id',$id)->setField('notcheck','0')){
	          $res = ['code'=>'1','msg'=>'检测','btn'=>'0','url'=>url('admin/Sys/menu')];
	        }else{
	          $res = ['code'=>'0','msg'=>'修改失败'];
	        }
	      }else{
	          if($this->where('id',$id)->setField('notcheck','1')){
	          $res = ['code'=>'1','msg'=>'不检测','btn'=>'1','url'=>url('admin/Sys/menu')];
	        }else{
	          $res = ['code'=>'0','msg'=>'修改失败'];
	        }
	      }
	      return $res;
	  }
	/**
	 * 获取权限菜单
	 * @return [type] [description]
	 */
	public function get_menu(){
		$admin_id = session('admin_user.id');
		$where = [];
		if(!in_array($admin_id,$this->nocheck_id)){
	        $auth = new Auth();
	        $menu_id = $auth->getAuthList($admin_id,1,'id');
	        $where['id'] = ['in',$menu_id];
		}
		$where['status'] = '1';
		$menu = Db::name('auth_rule')->where($where)->order('sort,id')->select();
		$tree = new \Tree();
		$tree->init($menu);
		$auth_menu = $tree->get_list();
		return $auth_menu;
	}
	/**
	 * 得到当前操作下的所有父id包含自己
	 * @return [type] [description]
	 */
	public function get_parents_id($self = 'false'){
        $menu_id = $this->get_menu_id();
        $menu = self::find($menu_id);
        $menu_all = self::select();
        $tree = new \Tree();
		$tree->init($menu_all);
		$auth_menu = $tree->get_parents_id($menu);
		if($self == 'true'){
			array_push($auth_menu,$menu['id']);
		}
		return $auth_menu;
	}
	/**
	 * 获取url对应的id
	 * @param  string $url [description]
	 * @return [type]      [-1：不需要检测，0：不存在，$menu_id:对应的id]
	 */
	public function get_menu_id($url = ''){

		$url = $url?$url:request()->module().'/'.request()->controller().'/'.request()->action();
		//过滤不需要检查的url
		if(in_array($url,$this->nocheck_url)) return -1;

        $menu_id = self::where('name',$url)->value('id');
        if(!$menu_id) return 0;
        return $menu_id;
	}
	/**
	 * 得到面包屑导航
	 * @param  [type] $idarr [description]
	 * @return [type]        [description]
	 */
	public function get_bread_crumbs($idarr){
       // $id = $this->get_parents_id('true');
       $bread_crumbs = $this->where('id','in',$idarr)->select();
       return $bread_crumbs;
	}
	/**
	 * 检测权限
	 * @return [type] [description]
	 */
	public function check_auth(){
		$admin_id = session('admin_user.id');
		$where = [];
		if(!in_array($admin_id,$this->nocheck_id)){
	        $auth = new Auth();
	        $check_id = array($this->get_menu_id());
	        $check_auth = $auth->check($check_id, $admin_id, 1, 'id');
	        return $check_auth;
		}
		return true;
	}
	/**
	 * 得到包含自己以及所有子类的id
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function get_child_id($id,$self = 'false'){
        $menu_all = self::select();
        $tree = new \Tree();
		$tree->init($menu_all);
		$child_id = $tree->get_child_id($id);
		if($self == 'true'){
			array_push($child_id,$id);
		}
		return $child_id;
	}
}